package cn.sskxyz.security.authorization.web.controller;

import cn.sskxyz.mybatis.mode.Page;
import cn.sskxyz.security.authorization.model.Oauth2Client;
import cn.sskxyz.security.authorization.model.SecurityService;
import cn.sskxyz.security.authorization.service.Oauth2ClientService;
import cn.sskxyz.security.authorization.web.args.ClientInfoArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class ClientController {

    @Autowired
    private Oauth2ClientService clientService;

    /**
     * 查询客户端列表
     * @param currentPage
     * @param pageSize
     * @return
     */
    @PostMapping("/client/list")
    public ResponseEntity<Page<List<Oauth2Client>>> getClientList(@RequestParam(defaultValue = "1", required = false) int currentPage,
                                                                  @RequestParam(defaultValue = "10", required = false) int pageSize) {
        Page<List<Oauth2Client>> clients = clientService.queryClientList(currentPage, pageSize);
        return ResponseEntity.ok(clients);
    }

    /**
     * 查询某客户端详细信息
     * @param clientId
     * @return
     */
    @GetMapping("/client/{clientId}")
    public ResponseEntity<Oauth2Client> getClientById(@PathVariable String clientId) {
        Oauth2Client client = clientService.loadClientByClientId(clientId);
        if (client == null) {
            return ResponseEntity.noContent().build();
        }
        return ResponseEntity.ok(client);
    }

    /**
     * 查询某客户端id可访问的服务列表
     *
     * @param clientId
     * @return
     */
    @GetMapping("/client/{clientId}/service")
    public ResponseEntity<List<SecurityService>> getClientService(@PathVariable String clientId) {
        List<SecurityService> services = clientService.queryServiceListByClientId(clientId);
        return ResponseEntity.ok(services);
    }

    /**
     * 添加客户端
     * @param client
     * @return
     */
    @PostMapping("/client")
    public ResponseEntity<Oauth2Client> addOauth2Client(@RequestBody ClientInfoArgs client) {
        Oauth2Client oauth2Client = clientService.addOauth2Client(client);
        return ResponseEntity.ok(oauth2Client);
    }

    /**
     * 修改客户端信息
     * @param clientInfoArgs
     * @return
     */
    @PutMapping("/client")
    public ResponseEntity updateClient(@RequestBody ClientInfoArgs clientInfoArgs) {
        Oauth2Client client = clientService.loadClientByClientId(clientInfoArgs.getClientId());
        if (client == null) {
            return ResponseEntity.noContent().build();
        }
        clientService.changeClientInfo(clientInfoArgs);
        return ResponseEntity.ok().build();
    }
}
